import { Context } from 'egg';

// 这里是你自定义的中间件
export default function json(): any {
    return async (ctx: Context, next: () => Promise<any>) => {
        // 你可以获取 config 的配置：
        let body = {
            code: 200,
            data: {},
            msg: 'ok',
        };
        let data: any = {}, msg = 'ok', code = 200;
        try {
            await next();
            data = ctx.body || {};
            if (data) {
                ctx.body = data;
            }
        } catch (error) {
            console.error(error);
            ctx.status = 200;
            // @ts-ignore
            let message = error?.message?.split('|');
            let [messageStr, messageCode] = message;
            msg = messageStr || '系统有误';
            if (messageCode) {
                code = messageCode;
            } else {
                code = 500;
            }
        }
        if (data == undefined || data == null || data == '') {
            data = {};
        }
        if (ctx.status != 200 && ctx.status != 204) {
            switch (ctx.status) {
                case 404:
                    msg = '接口不存在'
                    break;
                case 500:
                    msg = '系统有误'
                    break;
                default:
                    msg = '系统有误'
                    break;
            }
            code = ctx.status;
        }

        body.code = code;
        body.msg = msg;
        body.data = data;

        ctx.body = body;
    };
}